import json
import sys
import typing

import requests
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtNetwork import QHostAddress, QUdpSocket
from PyQt5.QtWidgets import QApplication, QWidget

from Ui_MainWidget import Ui_MainWidget


class MainWidget(QWidget):
    def __init__(self, parent: typing.Optional['QWidget'], flags: typing.Union[QtCore.Qt.WindowFlags, QtCore.Qt.WindowType]) -> None:
        super().__init__(parent=parent, flags=flags)
        self.__ui = Ui_MainWidget()
        self.__ui.setupUi(self)
        self.__udp_socket = QUdpSocket(self)
        with open('settings.json', mode='r') as json_file:
            dict_temp_ = json.load(json_file)
            self.__remoteIp = dict_temp_['remoteIp']
            self.__remotePort = dict_temp_['remotePort']
            self.__LoginUrl = dict_temp_['LoginUrl']
            self.__EditorUrl = dict_temp_['EditorUrl']

        self.__ui.pushButtonEitor.clicked.connect(self.__SlotPushbuttonEditorClicked)
        self.__ui.pushButtonSignin.clicked.connect(self.__SlotPushbuttonSigninClicked)
        self.__ui.pushButtonTrigger.clicked.connect(self.__SlotPushbuttonTriggerClicked)

    def __SlotPushbuttonSigninClicked(self) -> None:
        data_ = {
            'pskey':'sdzp-add-euser',
            'euser':{
                'rfid':self.__ui.lineEditRFID.text(),
                'name':self.__ui.lineEditName.text()
            }
        }
        head_ = {
            'Content-Type':'application/json;charset=UTF-8'
        }
        res_ = requests.post(self.__LoginUrl, data=json.dumps(data_), headers=head_)
        self.__ui.textEdit.append(res_.text)

    def __SlotPushbuttonEditorClicked(self) -> None:
        url_ = self.__EditorUrl + self.__ui.lineEditRFIDEditor.text()
        res_ = requests.get(url_)
        self.__ui.textEdit.append(res_.text)

    def __SlotPushbuttonTriggerClicked(self) -> None:
        pay_load_ = '01'.encode('utf-8')
        self.__udp_socket.writeDatagram(pay_load_, QHostAddress(self.__remoteIp), self.__remotePort)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWidget(None, Qt.Widget)
    mw.show()
    sys.exit(app.exec_())
